package com.cmcc.example.face.withSdk.service;

import com.alibaba.fastjson.JSON;
import com.chinamobile.bcop.api.sdk.ai.contentcensor.AiContentCensor;
import com.chinamobile.bcop.api.sdk.ai.facebody.FaceMatchRequest;
import com.chinamobile.bcop.api.sdk.constant.Region;
import com.chinamobile.bcop.api.sdk.exception.ClientException;
import com.chinamobile.bcop.api.sdk.modle.CommonJsonObjectResponse;
import com.cmcc.example.face.noSdk.common.vo.response.EcloudBaseResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * <p>
 * <name>SdkFaceService</name>
 * 调用sdk人脸检测相关逻辑
 * </p >
 *
 * @author arabira
 * @version 1.0 2020-04-03
 * @since 1.0
 */
@Slf4j
@Service
public class SdkFaceService {

    @Value("${cmcc.ecloud.apiKey}")
    private String clientId;
    @Value("${cmcc.ecloud.secretKey}")
    private String clientSecret;

    public EcloudBaseResponseVO matcher(MultipartFile image1, MultipartFile image2) throws IOException, ClientException {
        String img1Base64 = new BASE64Encoder().encode(image1.getBytes());
        String img2Base64 = new BASE64Encoder().encode(image2.getBytes());
        log.info("序列化图片信息为base64编码 \nimage1:{} \n\nimage2:{}", img1Base64, img2Base64);
        //设置客户端
        AiContentCensor aiContentCensor = new AiContentCensor(Region.POOL_NJ, clientId, clientSecret);
        //选择人脸对比功能
        FaceMatchRequest faceMatchRequest = new FaceMatchRequest();
        //使用文件对比
        faceMatchRequest.setImageFile1(img1Base64);
        faceMatchRequest.setImageFile2(img2Base64);
        //使用网络资源
//        faceMatchRequest.setImageUrl1("http://xxx/1.jpg");
//        faceMatchRequest.setImageUrl2("http://xxx/2.jpg");
        //发送请求并接收结果
        CommonJsonObjectResponse jsonObjectResponse = aiContentCensor.execute(faceMatchRequest);

        log.info("{}", JSON.toJSON(jsonObjectResponse));
        return null;
    }
}